﻿using WeixinSB.Common;
using WeixinSB.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using LYL.Common.RT.Text;
using WeixinSB.Model;
using Windows.Storage;
using WeixinSB.View;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Graphics.Imaging;
using System.Threading.Tasks;
using Windows.ApplicationModel.Store;
using WeixinSB.Tools;
using Windows.UI;
using MSPrize.View;
using WeixinSB.Service;
using Windows.ApplicationModel;
using LYL.Common.RT;

// The Pivot Application template is documented at http://go.microsoft.com/fwlink/?LinkID=391641

namespace WeixinSB
{
    /// <summary>
    /// A page that displays details for a single item within a group.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        WeixinSbModel weixin = new WeixinSbModel();

        private readonly NavigationHelper navigationHelper;
        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();



        public MainPage()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            this.MessageBox.Visibility = Visibility.Collapsed;

            //RT好疼，非得这么搞，binding不行，为毛线 微软，你逗我是不是啊。（老刘说这是RT的bug）
            ic.Visibility = Visibility.Collapsed;
            ac.Visibility = Visibility.Collapsed;
            wc.Visibility = Visibility.Collapsed;

            this.Loaded += async (s, e) =>
            {
                await Task.Delay(100);
                this.MessageBox.Visibility = Visibility.Visible;
                if (weixin.IphoneOpacity < 1)
                {
                    ic.Visibility = Visibility.Visible;
                }

                if (weixin.AndroidOpacity < 1)
                {
                    ac.Visibility = Visibility.Visible;
                }

                if (weixin.WpOpacity < 1)
                {
                    wc.Visibility = Visibility.Visible;
                }
            };

            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
           
        }

        void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
        {
            Application.Current.Exit();
        }

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        ///// <summary>
        ///// Gets the view model for this <see cref="Page"/>.
        ///// This can be changed to a strongly typed view model.
        ///// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data.
            //var item = await SampleDataSource.GetItemAsync((string)e.NavigationParameter);
            //this.DefaultViewModel["Item"] = item;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/>.</param>
        /// <param name="e">Event data that provides an empty dictionary to be populated with
        /// serializable state.</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: Save the unique state of the page here.
        }

        #region NavigationHelper registration

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
            //var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            //statusBar.BackgroundColor = new Color { R = 185, G = 193, B = 206 };
            //statusBar.ForegroundColor = Colors.White;
            //statusBar.BackgroundOpacity = 1;
            //Init
            weixin = await TemplateDataST.Get();

            if (weixin != null && weixin.CommentList != null && weixin.CommentList.Count > 0)
            {
                // _.IsChecked == true &&
                var result = weixin.CommentList
                     .Where(_ => !string.IsNullOrEmpty(_.UserName))
                     .ToList();

                weixin.CommentList = result;
            }
            await Task.Delay(100);
            this.DataContext = weixin;

            this.navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private void Template_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(TemplatePage));
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(EditPage));
        }

        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            await PicLibrary.Save(LayoutRoot);
            Show("保存到相册成功！:)");
        }

        private async void Comment_Click(object sender, RoutedEventArgs e)
        {
            var uri = new Uri(string.Format(@"ms-windows-store:reviewapp?appid={0}", Config.AppId));//商店根据appid跳转评论

            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private async void Update_Click(object sender, RoutedEventArgs e)
        {
            var uri = new Uri(string.Format(@"ms-windows-store:navigate?appid={0}", Config.AppId));//商店根据appid跳转
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(AboutPage));
        }


        private void Home_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(HomePage));
        }

        private void Send_Click(object sender, RoutedEventArgs e)
        {
            CommentDialogPage dialog = new CommentDialogPage
            {

            };
            dialog.Closed += dialog_Closed;
            dialog.Show();
        }

        async void dialog_Closed(object sender, InputEventArgs e)
        {
            string text = e.Text;
            if (text.J_HasAnyText())
            {
                try
                {
                    await StorageFileEx.SaveImage("test.png", LayoutRoot);
                    loading.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    var models = DeviceInfo.SystemManufacturer;
                    var productName = DeviceInfo.SystemProductName;
                    UploadService upload = new UploadService();
                    // 构造需要上传的文件数据
                    StorageFile file2 = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/test.png", UriKind.Absolute));
                    var stream2 = await file2.OpenReadAsync();
                    await upload.UploadFile(e.Text, Config.Type, models,productName, stream2.AsStream().AsInputStream());

                    Show("发布成功！:)");
                }
                catch (Exception ex)
                {
                    Show("发布失败！:(");
                }
                finally
                {
                    loading.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }

            }
        }

        void Show(string content)
        {
            MessageContent.Text = content;
            MessageIn.Begin();
        }

    }
}